﻿using System;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Reflection.Emit;

namespace scanAPP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        //自定义变量
        // private int port;
        private string Addr;
        private bool[] done = new bool[65536];
        private int start;
        private int end;
        //  private Thread scanThread;
        private bool OK;
        private void txtStart_TextChanged(object sender, System.EventArgs e)
        {
            //获取输入的起始端口值
            textBox1.Text = textBox2.Text;
        }
        private void txtEnd_TextChanged(object sender, System.EventArgs e)
        {
            //获取输入的结束端口值
            textBox2.Text = textBox3.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //创建线程，并创建ThreadStart委托对象
            Thread process = new Thread(PortScan);
            process.Start();
            //显示端口扫描的范围
            progressBar1.Minimum = Int32.Parse(textBox2.Text);
            progressBar1.Maximum = Int32.Parse(textBox3.Text);
            //显示框初始化
            listBox1.Items.Clear();
            listBox1.Items.Add("端口扫描器 v1.0.");
            listBox1.Items.Add("");
        }
        private void PortScan()
        {
            start = Int32.Parse(textBox2.Text);
            end = Int32.Parse(textBox3.Text);
            //检查输入范围合法性
            if ((start >= 0 && start <= 65536) && (end >= 0 && end <= 65536) && (start <= end))
            {
                listBox1.Items.Add("开始扫描... (可能需要请您等待几分钟)");
                Addr = textBox1.Text;
                for (int i = start; i <= end; i++)
                {
                    progressBar1.Value = i;
                    label6.Text = i.ToString();
                    try
                    {
                        TcpClient tcp = new TcpClient(Addr, i);
                        listBox1.Items.Add("端口 " + i.ToString() + " 开放！");
                    }
                    catch
                    {
                    }
                }
                while (!OK)
                {
                    OK = true;
                    for (int i = start; i <= end; i++)
                    {
                        if (!done[i])
                        {
                            OK = false;
                            break;
                        }
                    }
                    Thread.Sleep(1000);
                }
                listBox1.Items.Add("扫描结束!");
            }
            else
            {
                MessageBox.Show("输入错误，端口范围为[0-65536]");
            }
        }
    }
}
